﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _46_窗体拼图
{
    public partial class FormTry : Form
    {
        PictureBox[] fPictures;
        Random fRandom = new Random();
        public FormTry()
        {
            InitializeComponent();
            Bitmap fImage1 = Properties.Resources.DogBoy;
            Bitmap fImage = new Bitmap(fImage1, 300, 300);
            PictureBox pic = new PictureBox();
            Rectangle r1 = new Rectangle(0, 0, 300, 300);
            pic.Bounds = r1;
            pic.Image = fImage;

            this.panelShow.Controls.Add(pic);
            fPictures = new PictureBox[9];
            for (int i = 0; i < fPictures.Length; i++)
            {
                Rectangle r = new Rectangle(i % 3 * 100, i / 3 * 100, 100, 100);
                fPictures[i] = new PictureBox();
                fPictures[i].BorderStyle = BorderStyle.Fixed3D;
                fPictures[i].Bounds = r;
                fPictures[i].Tag = fPictures[i].Location;
                fPictures[i].Image = fImage.Clone(r, fImage.PixelFormat);
                this.pnlButtons.Controls.Add(fPictures[i]);
                fPictures[i].Click += new EventHandler(fPictures_Click);
            }
        }

        void fPictures_Click(object sender, EventArgs e)
        {
            PictureBox lPicture = sender as PictureBox;
            if (!((lPicture.Top == fPictures[8].Top && Math.Abs(lPicture.Left - fPictures[8].Left) == 100) ||
                (lPicture.Left == fPictures[8].Left && Math.Abs(lPicture.Top - fPictures[8].Top) == 100)))
                return;
            Point lLocation = lPicture.Location;
            lPicture.Location = fPictures[8].Location;
            fPictures[8].Location = lLocation;

            

            bool lFinished = true;
            foreach (PictureBox pic in fPictures)
                if (!pic.Location.Equals(pic.Tag))
                {
                    lFinished = false;
                    break;
                }
            if (lFinished)
                MessageBox.Show("完成！");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                int a = fRandom.Next(8);
                int b = fRandom.Next(8);

                Point lLocation = fPictures[a].Location;
                fPictures[a].Location = fPictures[b].Location;
                fPictures[b].Location = lLocation;
            }
            fPictures[8].Visible = false;
        }
    }
}